package top.infopub.mgr.bpa.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.enums.bpa.BpaProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.bpa.dao.*;
import top.infopub.mgr.bpa.domain.SubpackCotDomain;
import top.infopub.mgr.bpa.domain.SubpackLedgerDomain;
import top.infopub.mgr.bpa.jsonVo.SubpackCotJsonVo;
import top.infopub.mgr.bpa.service.BpaProcessManageService;
import top.infopub.mgr.bpa.service.SubpackCotService;
import top.infopub.mgr.bpa.vo.ContractManageVo;
import top.infopub.mgr.bpa.vo.SubpackCotVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.model.bpa.*;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service
public class SubpackCotServiceImpl extends GenericServiceImpl<SubpackCot, String> implements SubpackCotService {

    @Autowired
    private SubpackCotDao subpackCotDao;

    @Autowired
    private InnerAgrtDao innerAgrtDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private BpaProcessManageService bpaProcessManageService;

    @Override
    public GenericDao<SubpackCot, String> getDao() {
        return subpackCotDao;
    }

//    @Override
//    public List<SubpackCotDomain> selectByProCode(String proCode) {
//        return subpackCotDao.selectByProCode(proCode);
//    }

    @Override
    public Page<SubpackCotDomain> selectByDomainWhere(Page<SubpackCotDomain> page,
                                                      SubpackCotVo subpackCotVo) throws ParseException {
        //处理时间范围
        if (!StringUtils.isEmpty(subpackCotVo.getDates()))
        {
            String[] splitTime = subpackCotVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            subpackCotVo.setStartDate(format.parse(splitTime[0]));
            subpackCotVo.setEndDate(format.parse(splitTime[1]));
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<SubpackCotDomain>)subpackCotDao.selectByDomainWhere(subpackCotVo);
    }

    @Override
    public Page<SubpackLedgerDomain> selectByLedger(Page<SubpackLedgerDomain> page, ContractManageVo contractManageVo) throws ParseException {
        //处理时间范围
        if (!StringUtils.isEmpty(contractManageVo.getDates()))
        {
            String[] splitTime = contractManageVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            contractManageVo.setStartDate(format.parse(splitTime[0]));
            contractManageVo.setEndDate(format.parse(splitTime[1]));
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<SubpackLedgerDomain>)subpackCotDao.selectByLedger(contractManageVo);
    }

    @Override
    public RspVo queryPackDetail(String id) {
        SubpackCotJsonVo jsonVo = new SubpackCotJsonVo();
        //查询主表数据
        SubpackCot subpackCot = subpackCotDao.selectByPrimaryKey(id);
        jsonVo.setSubpackCot(subpackCot);
        if (StringUtils.equals("1",subpackCot.getContType())){//整体下浮
            //子项信息---
            List<InnerListing> innerListings = innerAgrtDao.selectListing(id,"3");
            jsonVo.setInnerListings(innerListings);
        }else{ //清单模式
            List<SubpackCotList> cotLists =  subpackCotDao.selectSup(id);
            jsonVo.setCotLists(cotLists);
        }
        //综合计划
        List<BpaCompPlan> compPlan = innerAgrtDao.selectPlan(subpackCot.getId(),"3");
        jsonVo.setCompPlan(compPlan);
        List<ProjectAttachment> attachmentList = projectAttachmentDao.queryByWhere(subpackCot.getProCode(), ProjectFileTypeEnum.FILE_TYPE87.getCode(), null);
        jsonVo.setFileAtt(fileAttaListToArray(attachmentList));
        return RspVo.getSuccessResponse(jsonVo);
    }

    @Override
    @Transactional
    public RspVo saveAll(String bodyStr, Integer submitType, AuthorizationVO userDtl, SubpackCot subpackCot, List<InnerListing> innerListings, List<SubpackCotList> cotLists, List<BpaCompPlan> compPlan,List<ProjectAttachment> attachmentList) {
        final String type = "3"; //分包合同评审
        if (StringUtils.isNotBlank(subpackCot.getId())){//编辑
            subpackCot.setUptBy(userDtl.getId());
            subpackCot.setUptTime(new Date());
           subpackCotDao.updateByPrimaryKey(subpackCot);
       }else{//新增
            subpackCot.setId(IdFactory.getUUIDUpper());
            subpackCot.setAddBy(userDtl.getId());
            subpackCot.setAddTime(new Date());
            subpackCotDao.insertById(subpackCot);
       }
       if (StringUtils.equals("1",subpackCot.getContType())){ //整体下浮

           innerAgrtDao.deleteListing(subpackCot.getId(),type);
           int seq = 0;
           for (InnerListing innerListing : innerListings) {
               innerListing.setInnerId(subpackCot.getId());
               innerListing.setType(type);
               innerListing.setSeq(seq++);
           }
           innerAgrtDao.insertBatchListing(innerListings);
       }else{//清单模式
           for (SubpackCotList cotList : cotLists) {
               cotList.setSubpackCotId(subpackCot.getId());
               cotList.setAddBy(userDtl.getId());
               cotList.setAddTime(new Date());
           }
           subpackCotDao.insertBatchCotList(cotLists);
       }
        //处理综合计划
        innerAgrtDao.deletePlan(subpackCot.getId(),type);
        for (BpaCompPlan bpaCompPlan : compPlan) {
            bpaCompPlan.setContractId(subpackCot.getId());
            bpaCompPlan.setType(type);
        }
        innerAgrtDao.insertBatchPlan(compPlan);

        //处理附件
        if (attachmentList!=null && attachmentList.size()>0){
            //批量插入附件信息
            projectAttachmentDao.deleteByWhere(subpackCot.getProCode(), ProjectFileTypeEnum.FILE_TYPE87.getCode(), null);
            for (ProjectAttachment attachment : attachmentList) {
                attachment.setProCode(subpackCot.getProCode());
            }
            projectAttachmentDao.insertBatch(attachmentList);
        }
        if (submitType==2){
            bpaProcessManageService.sendProcess(BpaProcessDetailTypeEnum.PRO_NODE_TYPE9, bodyStr, subpackCot.getId(), subpackCot.getProCode(), userDtl);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public SubpackCot selectBySguid(String id) {
        return subpackCotDao.selectByPrimaryKey(id);
    }

    public String[] fileAttaListToArray(List<ProjectAttachment> list) {
        if (list == null || list.size() <= 0) return null;
        String[] attaArr = new String[list.size()];
        int index = 0;
        for (ProjectAttachment pa : list) {
            StringBuffer tmp = new StringBuffer();
            tmp.append(pa.getSubTypes());
            tmp.append("|");
            tmp.append(pa.getFileName());
            tmp.append(pa.getFileSuffix());
            tmp.append("|");
            tmp.append(IdFactory.getUUIDSerialNumber());
            tmp.append("|");
            tmp.append(pa.getFilePath());
            attaArr[index] = tmp.toString();
            index++;
        }
        return attaArr;
    }

//    @Override
//    public Page<SubpackCotDomain> selectMyCheckByDomainWhere(Page<SubpackCotDomain> page,
//                                                             SubpackCotVo subpackCotVo) {
//        PageHelper.startPage(page.getPageNum(), page.getPageSize());
//        return (Page<SubpackCotDomain>)subpackCotDao.selectMyCheckByDomainWhere(subpackCotVo);
//    }
//
//    @Override
//    public List<SubpackCot> isExistSubpackCotName(String subpackCotName,String proCode) {
//        return subpackCotDao.isExistSubpackCotName(subpackCotName,proCode);
//    }
//
//    @Override
//    public List<SubpackCot> isExistSubpackCotSaName(String subpackCotSaName,String proCode) {
//        return subpackCotDao.isExistSubpackCotSaName(subpackCotSaName,proCode);
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void saveSubpackCot(SubpackCot subpackCot, List<SubpackCotSub> subpackCotSubs,
//                               List<SubpackCotDetail> subpackCotDetails,
//                               List<SubpackCotList> subpackCotLists,
//                               List<SubpackCotRate> subpackCotRates,
//                               List<SubpackCotAtt> subpackCotAtts) {
//        //添加分包合同主表
//        subpackCotDao.insertById(subpackCot);
//
//        //添加分包合同清单分解子项
//        if (CollectionUtils.isNotEmpty(subpackCotSubs)) {
//            subpackCotSubDao.insertByBatch(subpackCotSubs);
//        }
//
//        //添加分包合同清单分解子项费用明细
//        if (CollectionUtils.isNotEmpty(subpackCotDetails)) {
//            subpackCotDetailDao.insertByBatch(subpackCotDetails);
//        }
//
//        //添加分包合同价款信息-清单模式
//        if (CollectionUtils.isNotEmpty(subpackCotLists)) {
//            subpackCotListDao.insertByBatch(subpackCotLists);
//        }
//
//        //添加分包合同对应月度付款比例
//        if (CollectionUtils.isNotEmpty(subpackCotRates)) {
//            subpackCotRateDao.insertByBatch(subpackCotRates);
//        }
//
//        //添加附件
//        if (CollectionUtils.isNotEmpty(subpackCotAtts)) {
//            subpackCotAttDao.insertByBatch(subpackCotAtts);
//        }
//
//        // 注意 这里根据不同的业务分支判断条件 获得不同enum
//        FlowTemplateEnum templateEnum = FlowTemplateEnum.BPA_SUBPACK_COT;
//        // 处理工作流数据
//        wsFlowProcess.launch(templateEnum, subpackCot.getId(), subpackCot.getProcessId(), null);
//
//    }
//
//    @Override
//    public List<SubpackCot> selectSubpackCot() {
//        return subpackCotDao.selectSubpackCot(wsFlowProcess.proxyVisibleProCodes());
//    }
//
//    @Override
//    public SubpackCotDomain selectBySubpackCotVersionProCode(String proCode) {
//        return subpackCotDao.selectBySubpackCotVersionProCode(proCode);
//    }
//
//    @Override
//    public SubpackCot selectByProCodes(String proCode) {
//        return subpackCotDao.selectByProCodes(proCode);
//    }
//
//    @Override
//    public SubpackCot selectVersionNoByProCode(String proCode) {
//        return subpackCotDao.selectVersionNoByProCode(proCode);
//    }
//
//    @Override
//    public int countByName(String names) {
//        return subpackCotDao.countByName(names);
//    }
//
//    @Override
//    public SubpackCotVo queryById(String id) {
//        return subpackCotDao.queryById(id);
//    }
//
//    @Override
//    public SubpackCotDomain selectByRefId(String refId) {
//        return subpackCotDao.selectByRefId(refId);
//    }
//
//    @Override
//    public SubpackCotDomain selectById(String id) {
//        return subpackCotDao.selectById(id);
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void sign(SubpackCotVo subpackCotVo, List<SubpackCotAtt> subpackCotAtts) {
//        SubpackCot subpackCot = new SubpackCot();
//        subpackCot.setId(subpackCotVo.getId());
//        subpackCot.setSignDate(subpackCotVo.getSignDate());
//        subpackCot.setUptBy(SessionUserUtils.getSessionUserId());
//        subpackCot.setUptTime(DateUtils.getCurrentDateTime());
//        //更新记录
//        subpackCotDao.updateByIdSelective(subpackCot);
//
//        //补充附件
//        if(CollectionUtils.isNotEmpty(subpackCotAtts)){
//            subpackCotAttDao.insertByBatch(subpackCotAtts);
//        }
//
//    }
//
//    @Override
//    public BigDecimal sumPreScopeFee(String proCode) {
//        return subpackCotDao.sumPreScopeFee(proCode);
//    }
//
//    @Override
//    public BigDecimal sumAfterScopeFee(String proCode) {
//        return subpackCotDao.sumAfterScopeFee(proCode);
//    }

}
